using System;
using System.IO;
using System.IO.Compression;
using System.IO.IsolatedStorage;
using System.Threading;

using System.Web;
using System.Data;
using System.Text;
using System.Web.UI;
using System.Collections;
using System.Web.Security;
using System.Configuration;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls.WebParts;

using GonzalesCore.CoreElements;
using GonzalesCore.CoreManagers;
using Kypris2.CoreElements;
using Kypris2.Utils;
using Jamila2.Tools;
using SevenZip;

public partial class GonzalesReportAttachmentFiles : System.Web.UI.Page
{
    #region Variables
    protected PrivateLoginSession CurrentPrivateSession = null;
    protected LogManager CurLogManager = null;
    protected DataView ResultView = null;
    protected DataOBj CurPageDataObj = new DataOBj();

    protected static SupportingDocuments ResultDocuments = null;

    #region ResultTable
    protected DataTable ResultTable
    {
        get { return (DataTable)ViewState["ResultTable"]; }
        set { ViewState["ResultTable"] = value; }
    }
    #endregion

    #region UnexpectedError
    protected string UnexpectedError
    {
        get { return ViewState["UnexpectedError"].ToString(); }
        set { ViewState["UnexpectedError"] = value; }
    }
    #endregion

    #region NoDataAvailable
    protected string NoDataAvailable
    {
        get { return ViewState["NoDataAvailable"].ToString(); }
        set { ViewState["NoDataAvailable"] = value; }
    }
    #endregion

    #region SuccessfullExport2File
    protected string SuccessfullExport2File
    {
        get { return ViewState["SuccessfullExport2File"].ToString(); }
        set { ViewState["SuccessfullExport2File"] = value; }
    }
    #endregion

    #region Download
    protected string Download
    {
        get { return ViewState["Download"].ToString(); }
        set { ViewState["Download"] = value; }
    }
    #endregion

    #region DateRangeMessage
    protected string DateRangeMessage
    {
        get { return ViewState["DateRangeMessage"].ToString(); }
        set { ViewState["DateRangeMessage"] = value; }
    }
    #endregion

    #region ProperDateMessage
    protected string ProperDateMessage
    {
        get { return ViewState["ProperDateMessage"].ToString(); }
        set { ViewState["ProperDateMessage"] = value; }
    }
    #endregion

    #region GridViewHeader
    protected ArrayList GridViewHeader
    {
        get { return (ArrayList)ViewState["GridViewHeader"]; }
        set { ViewState["GridViewHeader"] = value; }
    }
    #endregion

    #region SelectLink
    protected string SelectLink
    {
        get
        {
            string text = (string)ViewState["SelectLink"];
            if (text != null) return text;
            else return string.Empty;
        }

        set { ViewState["SelectLink"] = value; }
    }
    #endregion

    #endregion

    #region Events

    protected void Page_Load(object sender, EventArgs e)
    {
        this.SessionCheck();

        this.Table_MessageBox.Visible = false;  // always default to false
        this.HyperLink_FileDownload.Visible = false;

        if (!IsPostBack)
        {
            this.PageComponentSetup();
            this.SwitchLanguage();
        }

        // Added by thangnv 20130730
        if (GonzalesGeneralVariables.SpecialUsers.Contains(this.CurrentPrivateSession.ActualLoginUser.EmailID))
        {
            this.TextBox_CostCenter.Text = GonzalesGeneralVariables.BuildInCostCenters();
            this.TextBox_CostCenter.Enabled = false;
        }
    }

    protected void Button_Submit_Click(object sender, EventArgs e)
    {
        bool valid = true;
        StringBuilder ErrorMessageBuilder = new StringBuilder("<ul>");

        #region Date Validation

        if (this.TextBox_SubmittedDateFrom.Text.Length == 0 || this.TextBox_SubmittedDateTo.Text.Length == 0)
        {
            ErrorMessageBuilder.AppendLine("<li>" + this.DateRangeMessage + "</li>");
            valid = false;
        }
        else
        {
            try
            {
                // try to convert to date
                DateTime Date1 = SwissArmy.DateConvert(this.TextBox_SubmittedDateFrom.Text, this.CurrentPrivateSession.CurrentLoggedOnUser.PreferedDateFormat);
                DateTime Date2 = SwissArmy.DateConvert(this.TextBox_SubmittedDateTo.Text, this.CurrentPrivateSession.CurrentLoggedOnUser.PreferedDateFormat);

                if (Date1 == DateTime.MinValue || Date2 == DateTime.MinValue)
                {
                    ErrorMessageBuilder.AppendLine("<li>"+ this.ProperDateMessage +"</li>");
                    valid = false;
                }
            }
            catch (Exception)
            {
                ErrorMessageBuilder.AppendLine("<li>" + this.ProperDateMessage + "</li>");
                valid = false;
            }
            
        }
        ErrorMessageBuilder.AppendLine("</ul>");
        #endregion

        if (this.DropDownList_ByCompany.SelectedIndex > 0 && valid)
        {
            this.LoadData();

            if (this.ResultTable != null)
            {
                //DataView ResultView = new DataView(this.ResultTable);
                this.BindData(this.ResultView);
            }
        }
        else
        {
            this.ShowErrorMessage(ErrorMessageBuilder.ToString());
        }
    }

    protected void Button_CSV_Click(object sender, EventArgs e)
    {
        bool valid = true;
        StringBuilder ErrorMessageBuilder = new StringBuilder("<ul>");

        #region Date Validation

        if (this.TextBox_SubmittedDateFrom.Text.Length == 0 || this.TextBox_SubmittedDateTo.Text.Length == 0)
        {
            ErrorMessageBuilder.AppendLine("<li>" + this.DateRangeMessage + "</li>");
            valid = false;
        }
        else
        {
            try
            {
                // try to convert to date
                DateTime Date1 = SwissArmy.DateConvert(this.TextBox_SubmittedDateFrom.Text, this.CurrentPrivateSession.CurrentLoggedOnUser.PreferedDateFormat);
                DateTime Date2 = SwissArmy.DateConvert(this.TextBox_SubmittedDateTo.Text, this.CurrentPrivateSession.CurrentLoggedOnUser.PreferedDateFormat);

                if (Date1 == DateTime.MinValue || Date2 == DateTime.MinValue)
                {
                    ErrorMessageBuilder.AppendLine("<li>" + this.ProperDateMessage + "</li>");
                    valid = false;
                }
            }
            catch (Exception)
            {
                ErrorMessageBuilder.AppendLine("<li>" + this.ProperDateMessage + "</li>");
                valid = false;
            }

        }
        ErrorMessageBuilder.AppendLine("</ul>");
        #endregion

        if (this.DropDownList_ByCompany.SelectedIndex > 0 && valid)
        {
            this.LoadData();

            if (ResultDocuments != null & ResultDocuments.Count <= 0) return;
            string FolderNameFiles = "SupportingDocumentFiles"; //DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString();
            string FolderNameZip = "SupportingDocumentZip";

            string FileZip = "Download-SupportingDocuments-" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + ".zip";
            DirectoryInfo di = new DirectoryInfo(Server.MapPath("ReportsOutput\\") + FolderNameFiles + "\\");

            if (di.GetFiles().Length > 0)
            {
                foreach (FileInfo fi in di.GetFiles())
                {
                    SwissArmy.FileDelete(fi.FullName);
                    Thread.Sleep(300);
                }
                Thread.Sleep(3000);
            }

            this.SaveFiles(FolderNameFiles);
            Thread.Sleep(300);

            di = new DirectoryInfo(Server.MapPath("ReportsOutput\\") + FolderNameFiles + "\\");
            //bool isCreated = CreateZip(Server.MapPath("ReportsOutput\\") + FolderNameZip + "\\" + FileZip);

            if (di.GetFiles().Length > 0)
            {
                this.ShowMessage(this.SuccessfullExport2File);
                // zip files
                /*if (!Compress(Server.MapPath("ReportsOutput\\") + FolderNameFiles + "\\", Server.MapPath("ReportsOutput\\") + FolderNameZip + "\\", FileZip)) return;

                this.HyperLink_FileDownload.Text = this.Download + FileZip;
                this.HyperLink_FileDownload.NavigateUrl = "ReportsOutput/" + FolderNameZip + "/" + FileZip;
                this.HyperLink_FileDownload.Visible = true;
                this.ShowMessage(this.SuccessfullExport2File);*/
            }
        }
        else
        {
            this.ShowErrorMessage(ErrorMessageBuilder.ToString());
        }
    }

    //private bool Compress(string srcFolder, string desFolder, string zipFName)
    //{
    //    try
    //    {
    //        SevenZipCompressor.SetLibraryPath(Server.MapPath("Bin\\7z.dll"));
    //        SevenZipCompressor compressor = new SevenZipCompressor();
    //        compressor.CompressDirectory(srcFolder, desFolder + zipFName);
    //    }
    //    catch (Exception ex)
    //    {
    //        this.ShowErrorMessage("Zip files error: " + ex.Message);
    //        return false;
    //    }
    //    return true;
    //}

    /*
    public static void Compress(FileInfo fi)
    {
        // Get the stream of the source file.

        using (FileStream inFile = fi.OpenRead())
        {
            // Prevent compressing hidden and already compressed files. 
            if ((File.GetAttributes(fi.FullName) & FileAttributes.Hidden) != FileAttributes.Hidden & fi.Extension != ".zip")
            {
                // Create the compressed file. 
                using (FileStream outFile = File.Create(fi.FullName + ".zip"))
                {
                    using (GZipStream Compress = new GZipStream(outFile, System.IO.Compression.CompressionMode.Compress))
                    {
                        // Copy the source file into the compression stream. 
                        byte[] buffer = new byte[4096];
                        int numRead;
                        while ((numRead = inFile.Read(buffer, 0, buffer.Length)) != 0)
                        {
                            Compress.Write(buffer, 0, numRead);
                        }
                    }
                }
            }
        }
    }*/

    /*
    public static void Decompress(FileInfo fi)
    {
        // Get the stream of the source file. 
        using (FileStream inFile = fi.OpenRead())
        {
            // Get original file extension, for example "doc" from report.doc.gz.
            string curFile = fi.FullName;
            string origName = curFile.Remove(curFile.Length - fi.Extension.Length);
            //Create the decompressed file. 
            using (FileStream outFile = File.Create(origName))
            {
                using (GZipStream Decompress = new GZipStream(inFile,
                        System.IO.Compression.CompressionMode.Decompress))
                {
                    //Copy the decompression stream into the output file. 
                    byte[] buffer = new byte[4096];
                    int numRead;
                    while ((numRead = Decompress.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        outFile.Write(buffer, 0, numRead);
                    }
                }
            }
        }
    } */

    protected void DropDownList_ByEntity_SelectedIndexChanged(object sender, EventArgs e)
    {
        using (CompanyManager CurCompanyManager = new CompanyManager(this.CurrentPrivateSession))
        {
            GonzalesCompanies ResultList = CurCompanyManager.GetCompanyByEntityID(this.DropDownList_ByEntity.SelectedValue);

            if (ResultList != null)
            {
                this.DropDownList_ByCompany.Items.Clear();
                this.DropDownList_ByCompany.Items.Add(new ListItem("", ""));

                for (int x = 0; x < ResultList.Count; x++)
                {
                    this.DropDownList_ByCompany.Items.Add(new ListItem(ResultList[x].CompanyName, ResultList[x].InternalID));
                }
            }
            else
            {
                this.CurLogManager.LogError("[GonzalesReportAttachmentFiles.DropDownList_ByEntity_SelectedIndexChanged] : Failed on CurCompanyManager.GetCompanyByEntityID('" + this.DropDownList_ByEntity.SelectedValue + "') : " + CurCompanyManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
            }
        }
        #region Filter the company by Finance Admin
        if (this.CurrentPrivateSession.CurrentLoggedOnUser.IsFinanceAdmin)
        {
            using (UserManager CurUserManager = new UserManager(this.CurrentPrivateSession))
            {
                GonzalesCompanies ResultCompanies = CurUserManager.GetCompanyByFinanceAdmin(this.CurrentPrivateSession.CurrentLoggedOnUser.InternalID);
                if (ResultCompanies != null)
                {
                    int x = 1;

                    while (x < this.DropDownList_ByCompany.Items.Count)
                    {
                        bool Matched = false;

                        for (int y = 0; y < ResultCompanies.Count; y++)
                        {
                            if (ResultCompanies[y].InternalID.CompareTo(this.DropDownList_ByCompany.Items[x].Value) == 0)
                            {
                                Matched = true;
                                break;
                            }
                        }

                        if (!Matched)
                        {
                            this.DropDownList_ByCompany.Items.RemoveAt(x);
                        }
                        else
                        {
                            x++;
                        }
                    }
                }
            }
        }
        #endregion
    }

    #region OnRowCreated
    protected void OnRowCreated(object sender, GridViewRowEventArgs e)
    {
        //TableCellCollection cells = e.Row.Cells;
        //if (e.Row.RowType == DataControlRowType.Header)
        //{
        //    CheckBox chkAll = new CheckBox();
        //    chkAll.ID = "chkAll"; 
        //    chkAll.AutoPostBack = true;
        //    cells[7].Controls.Add(chkAll);
        //    chkAll.CheckedChanged += new EventHandler(chkAll_CheckedChanged);
        //}
        //else
        //{
        //    CheckBox chkSelector = new CheckBox();
        //    chkSelector.ID = "chkSelector_" + e.Row.DataItemIndex;
        //    chkSelector.AutoPostBack = false;
        //    cells[7].Controls.Add(chkSelector);
        //}
    }
    #endregion

    #endregion

    #region Customized Methods

    #region SessionCheck
    public void SessionCheck()
    {

        if (Session[GonzalesCommonNamingConvention.CurrentPrivateSession] != null)
        {
            this.CurrentPrivateSession = (PrivateLoginSession)Session[GonzalesCommonNamingConvention.CurrentPrivateSession];
            this.CurLogManager = new LogManager(this.CurrentPrivateSession);    // activate Log Manager
        }
        else
        {
            Response.Redirect(GonzalesErrorPageRedirect.SessionError);
        }

    }
    #endregion

    #region PageComponentSetup
    protected void PageComponentSetup()
    {
        // browse button
        //this.Button_Browse.Attributes["onclick"] = "ShowModal('AddressBook', document.getElementById('ModalResult')); return false;";
        //this.TextBox_ClaimedByName.Attributes["onclick"] = "NoEdit(this);";

        // date
        //this.TextBox_SubmittedDateFrom.Attributes["onclick"] = "popUpCalendar(this, this, '" + SwissArmy.DateFormatForDisplay(this.CurrentPrivateSession.DateFormatInUse, "/") + "');";
        //this.TextBox_SubmittedDateTo.Attributes["onclick"] = "popUpCalendar(this, this, '" + SwissArmy.DateFormatForDisplay(this.CurrentPrivateSession.DateFormatInUse, "/") + "');";
        this.img_calendarFrom.Attributes["onClick"] = "popUpCalendar(this, document.getElementById('TextBox_SubmittedDateFrom') , '" + SwissArmy.DateFormatForDisplay(this.CurrentPrivateSession.DateFormatInUse, "/") + "');"; ;
        this.img_calendarTo.Attributes["onClick"] = "popUpCalendar(this, document.getElementById('TextBox_SubmittedDateTo') , '" + SwissArmy.DateFormatForDisplay(this.CurrentPrivateSession.DateFormatInUse, "/") + "');"; ;


        // setup entity
        if (this.CurrentPrivateSession.CurrentLoggedOnUser.IsPowerAdmin || this.CurrentPrivateSession.CurrentLoggedOnUser.IsITAdmin)
        {
            #region Power Admin/ IT Admin
            using (EntityManager CurEntityManager = new EntityManager(this.CurrentPrivateSession))
            {
                MasterBaseCollection ResultList = CurEntityManager.GetAllEntity();
                if (ResultList != null)
                {
                    this.DropDownList_ByEntity.Items.Add(new ListItem("", ""));
                    for (int x = 0; x < ResultList.Count; x++)
                    {
                        this.DropDownList_ByEntity.Items.Add(new ListItem(ResultList[x].DisplayName, ResultList[x].InternalID));
                    }
                }
                else
                {
                    // display error
                    this.CurLogManager.LogError("[GonzalesAdminClaimantsListing.PageComponentSetup] : Failed on CurEntityManager.GetAllEntity() : " + CurEntityManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);

                }
            }
            #endregion
        }
        else
        {
            #region Finance Admin

            using (UserManager CurManager = new UserManager(this.CurrentPrivateSession))
            {
                MasterBaseCollection ResultList = CurManager.GetEntityByFinanceAdmin(this.CurrentPrivateSession.CurrentLoggedOnUser.InternalID);
                if (ResultList != null)
                {
                    for (int x = 0; x < ResultList.Count; x++)
                    {
                        this.DropDownList_ByEntity.Items.Add(new ListItem(ResultList[x].DisplayName, ResultList[x].InternalID));
                    }
                }
                else
                {
                    // display error
                    this.CurLogManager.LogError("[GonzalesAdminClaimantsListing.PageComponentSetup] : Failed on CurEntityManager.GetAllEntity() : " + CurManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                }
            }

            #endregion
        }

        this.DropDownList_ByEntity_SelectedIndexChanged(null, null);

        //this.DropDownList_ReportType.Items.Add(new ListItem("Detail", "Detail"));
        //this.DropDownList_ReportType.Items.Add(new ListItem("Summary", "Summary"));

    }
    #endregion

    #region SwitchLanguage
    protected void SwitchLanguage()
    {
        try
        {
            using (MultiLingualFactory CurLanguageFactory = MultiLingualEngine.GetMultiLingualFactory(this, this.CurrentPrivateSession.CurrentLoggedOnUser.PreferedLanguage.InternalID))
            {
                //this.Label_Category.Text = CurLanguageFactory.DisplayValue("Category");
                //this.Label_ClaimedBy.Text = CurLanguageFactory.DisplayValue("ClaimedBy");
                this.Label_ClaimID.Text = CurLanguageFactory.DisplayValue("ClaimID");
                this.Label_Company.Text = CurLanguageFactory.DisplayValue("Company");
                this.Label_DateRange.Text = CurLanguageFactory.DisplayValue("DateRange");
                this.Label_Entity.Text = CurLanguageFactory.DisplayValue("Entity");
                this.Label_Information.Text = CurLanguageFactory.DisplayValue("Information");
                this.Label_PageTitle.Text = CurLanguageFactory.DisplayValue("PageTitle");
                //this.Label_Reasons.Text = CurLanguageFactory.DisplayValue("Reasons");
                //this.Label_Sorting.Text = CurLanguageFactory.DisplayValue("Sorting");
                //this.Label_Status.Text = CurLanguageFactory.DisplayValue("Status");
                this.Label_To.Text = CurLanguageFactory.DisplayValue("To");
                this.Label1.Text = CurLanguageFactory.DisplayValue("Label1");
                //this.Button_Browse.Text = CurLanguageFactory.DisplayValue("Browse");
                this.Button_CSV.Text = CurLanguageFactory.DisplayValue("CSV");
                this.Button_Submit.Text = CurLanguageFactory.DisplayValue("Submit");
                this.Download = CurLanguageFactory.DisplayValue("Download");
                this.UnexpectedError = CurLanguageFactory.DisplayValue("UnexpectedMessage");
                this.NoDataAvailable = CurLanguageFactory.DisplayValue("NoDataAvailable");
                this.DateRangeMessage = CurLanguageFactory.DisplayValue("DateRangeMessage");
                this.ProperDateMessage = CurLanguageFactory.DisplayValue("ProperDateMessage");
                this.SelectLink = CurLanguageFactory.DisplayValue("SelectLink");

                this.GridViewHeader = new ArrayList();
                this.GridViewHeader.Add(CurLanguageFactory.DisplayValue("ClaimID"));
                this.GridViewHeader.Add(CurLanguageFactory.DisplayValue("FileName"));
                this.GridViewHeader.Add(CurLanguageFactory.DisplayValue("FileType"));
                this.GridViewHeader.Add(CurLanguageFactory.DisplayValue("UploadDateInStr"));
                this.GridViewHeader.Add(CurLanguageFactory.DisplayValue("UploadedBy"));
                this.GridViewHeader.Add(CurLanguageFactory.DisplayValue("ProfitCenter"));
                this.GridViewHeader.Add(CurLanguageFactory.DisplayValue("SelectLink"));
                this.SuccessfullExport2File = CurLanguageFactory.DisplayValue("SuccessfullExport2File");

                // sort by
                //this.DropDownList_SortBy.Items.Add(new ListItem(CurLanguageFactory.DisplayValue("ClaimID2"), "ClaimID"));
                //this.DropDownList_SortBy.Items.Add(new ListItem(CurLanguageFactory.DisplayValue("Category2"), "Category"));
                //this.DropDownList_SortBy.Items.Add(new ListItem(CurLanguageFactory.DisplayValue("Status2"), "Status"));
                //this.DropDownList_SortBy.Items.Add(new ListItem(CurLanguageFactory.DisplayValue("LocalCurrency"), "LocalCurrency"));
                //this.DropDownList_SortBy.Items.Add(new ListItem(CurLanguageFactory.DisplayValue("AmountClaimed"), "AmountClaimed"));
                //this.DropDownList_SortBy.Items.Add(new ListItem(CurLanguageFactory.DisplayValue("FinalAmount"), "CostCenter"));
                //this.DropDownList_SortBy.Items.Add(new ListItem(CurLanguageFactory.DisplayValue("ClaimedBy"), "ClaimedBy"));
                //this.DropDownList_SortBy.Items.Add(new ListItem(CurLanguageFactory.DisplayValue("EmployeeID"), "EmployeeID"));
                //this.DropDownList_SortBy.Items.Add(new ListItem(CurLanguageFactory.DisplayValue("CostCenter"), "CostCenter"));

                //this.DropDownList_SortOrder.Items.Add(new ListItem(CurLanguageFactory.DisplayValue("ASC"), "ASC"));
                //this.DropDownList_SortOrder.Items.Add(new ListItem(CurLanguageFactory.DisplayValue("DESC"), "DESC"));
            }
        }
        catch (Exception ex)
        {
            this.CurLogManager.LogError("[GonzalesReportGeneralClaimants.SwitchLanguage.EX] : " + ex.Message, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.User);
        }

    }
    #endregion

    void chkAll_CheckedChanged(object sender, EventArgs e)
    {
        //CheckBox chkAll = (CheckBox)sender;
        //bool chkFlag = false;
        //if (chkAll.Checked) chkFlag = true;
        //for (int x = 0; x < this.GridViewResult.Rows.Count; x++)
        //{
        //    CheckBox CheckBoxApprove = (CheckBox)this.GridViewResult.Rows[x].Cells[7].Controls[0];
        //    CheckBoxApprove.Checked = chkFlag;
        //}
    }

    #region ShowErrorMessage
    protected void ShowErrorMessage(string ErrorMessage)
    {
        this.Table_MessageBox.Visible = true;
        this.Table_MessageBox.Rows[0].Cells[0].Text = ErrorMessage;
        this.Table_MessageBox.Rows[0].Cells[0].CssClass = "ErrorBox";
    }
    #endregion

    #region ShowMessage
    protected void ShowMessage(string Message)
    {
        this.Table_MessageBox.Visible = true;
        this.Table_MessageBox.Rows[0].Cells[0].Text = Message;
        this.Table_MessageBox.Rows[0].Cells[0].CssClass = "MessageBox";
    }
    #endregion

    #endregion

    #region Data Operation

    #region LoadData
    protected void LoadData()
    {
        using (FileManager CurFileManager = new FileManager(this.CurrentPrivateSession))
        {
            string lsCostCenters = string.Empty;
            if (this.TextBox_CostCenter.Text.Length > 0)
            {
                if (GonzalesGeneralVariables.SpecialUsers.Contains(this.CurrentPrivateSession.ActualLoginUser.EmailID))
                    lsCostCenters = " ( " + GonzalesGeneralVariables.BuildInCostCenters() + " ) ";
                else
                    lsCostCenters = " ( '" + this.TextBox_CostCenter.Text.Trim() + "' )";
            }

            ResultDocuments = CurFileManager.GetFilesByCompany(DropDownList_ByCompany.SelectedValue, 
                SwissArmy.DateConvert(this.TextBox_SubmittedDateFrom.Text, this.CurrentPrivateSession.CurrentLoggedOnUser.PreferedDateFormat), 
                SwissArmy.DateConvert(this.TextBox_SubmittedDateTo.Text, this.CurrentPrivateSession.CurrentLoggedOnUser.PreferedDateFormat),
                this.TextBox_ClaimID.Text.Trim(), lsCostCenters);

            if (ResultDocuments != null)
            {
                if (ResultDocuments.Count > 0)
                {
                    this.ResultTable = new DataTable();
                    this.ResultTable.Columns.Add(new DataColumn(this.CurPageDataObj.ClaimCode, Type.GetType("System.String")));
                    this.ResultTable.Columns.Add(new DataColumn(this.CurPageDataObj.FileName, Type.GetType("System.String")));
                    this.ResultTable.Columns.Add(new DataColumn(this.CurPageDataObj.FileType, Type.GetType("System.String")));
                    this.ResultTable.Columns.Add(new DataColumn(this.CurPageDataObj.UploadDate, Type.GetType("System.DateTime")));
                    this.ResultTable.Columns.Add(new DataColumn(this.CurPageDataObj.UploadDateInStr, Type.GetType("System.String")));
                    this.ResultTable.Columns.Add(new DataColumn(this.CurPageDataObj.UploadedBy, Type.GetType("System.String")));
                    this.ResultTable.Columns.Add(new DataColumn(this.CurPageDataObj.ProfitCenter, Type.GetType("System.String")));
                    this.ResultTable.Columns.Add(new DataColumn(this.CurPageDataObj.SelectLink, Type.GetType("System.String")));
                    this.ResultTable.Columns.Add(new DataColumn("chkAll", Type.GetType("System.Boolean")));
                    this.ResultTable.Columns.Add(new DataColumn(this.CurPageDataObj.InternalID, Type.GetType("System.String")));

                    foreach (SupportingDocument ResultDoc in ResultDocuments)
                    {

                        DataRow ResultRow = this.ResultTable.NewRow();
                        ResultRow[this.CurPageDataObj.ClaimCode] = ResultDoc.ClaimCode;
                        string[] filename = SwissArmy.StringSplit(ResultDoc.FileName, "\\");

                        ResultRow[this.CurPageDataObj.FileName] = filename[filename.Length - 1].ToString();
                        ResultRow[this.CurPageDataObj.FileType] = ResultDoc.FileType;
                        ResultRow[this.CurPageDataObj.UploadDate] = ResultDoc.UploadDate;
                        ResultRow[this.CurPageDataObj.UploadDateInStr] = SwissArmy.DateConvert(ResultDoc.UploadDate, this.CurrentPrivateSession.DateFormatInUse, "/");
                        ResultRow[this.CurPageDataObj.UploadedBy] = ResultDoc.UploadedBy.DisplayName + " (" + ResultDoc.UploadedBy.EmailID + ") ";
                        ResultRow[this.CurPageDataObj.ProfitCenter] = ResultDoc.UploadedBy.CostCenter;
                        ResultRow[this.CurPageDataObj.SelectLink] = "<a href='GonzalesViewFile.aspx?id=" + ResultDoc.InternalID + "' target='newdoc' class='GridViewLink'>" + this.SelectLink + "</a>";
                        ResultRow[this.CurPageDataObj.InternalID] = ResultDoc.InternalID;
                        this.ResultTable.Rows.Add(ResultRow);
                    }

                    this.ResultView = new DataView(this.ResultTable);
                }
                else
                {
                    this.ShowMessage(this.NoDataAvailable);                
                }
                // filter ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                /*StringBuilder FilterBuilder = new StringBuilder();

                if (this.TextBox_ClaimID.Text.Trim().Length > 0)
                {
                    FilterBuilder.Append(((FilterBuilder.Length > 0) ? " AND " : "") + "ClaimCode = '" + this.TextBox_ClaimID.Text + "'");
                }

                if (this.TextBox_CostCenter.Text.Length > 0)
                {
                    if (GonzalesGeneralVariables.SpecialUsers.Contains(this.CurrentPrivateSession.ActualLoginUser.EmailID))
                        FilterBuilder.Append(((FilterBuilder.Length > 0) ? " AND " : "") + "ProfitCenter IN ( " + GonzalesGeneralVariables.BuildInCostCenters() + " ) ");
                    else
                        FilterBuilder.Append(((FilterBuilder.Length > 0) ? " AND " : "") + "ProfitCenter = '" + this.TextBox_CostCenter.Text + "' ");
                }

                this.ResultView.RowFilter = FilterBuilder.ToString();*/
                //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

                //this.ResultView.Sort = this.DropDownList_SortBy.SelectedValue + " " + this.DropDownList_SortOrder.SelectedValue;
            }
            else
            {
                string LogID = SwissArmy.UniqueID();
                this.CurLogManager.LogError(LogID, "[GonzalesReportAttachmentFiles.LoadData] : Failed at CurFileManager.GetFilesByCompany('" + this.DropDownList_ByCompany.SelectedValue + ", " + this.TextBox_SubmittedDateFrom.Text + ", " + this.TextBox_SubmittedDateTo.Text + "') : " + CurFileManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                this.ShowErrorMessage(this.UnexpectedError + LogID);
            }
        }
    }

    #endregion

    #region BindData
    private void BindData(DataView result)
    {
        this.GridViewResult.DataSource = result;
        this.GridViewResult.DataBind();
    }

    private void BindData(DataView result, int pageindex)
    {
        this.GridViewResult.PageIndex = pageindex;
        this.GridViewResult.DataSource = result;
        this.GridViewResult.DataBind();
    }
    #endregion

    #endregion

    #region Class: DataOBj
    protected class DataOBj
    {
        public readonly string ClaimCode = "claim_code";
        public readonly string ProfitCenter     = "ProfitCenter";
        public readonly string FileName         = "FileName";
        public readonly string FileType         = "FileType";
        public readonly string UploadDate       = "UploadDate";
        public readonly string UploadDateInStr  = "UploadDateInStr";
        public readonly string UploadedBy       = "UploadedBy";
        public readonly string SelectLink       = "SelectLink";
        public readonly string InternalID       = "internal_id";
    }
    #endregion
    protected void GridViewResult_DataBound(object sender, EventArgs e)
    {

    }
    protected void GridViewResult_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //TableCellCollection cells = e.Row.Cells;
        // if (e.Row.RowType != DataControlRowType.Header)
        // {
        //     CheckBox ckApprove = new CheckBox();
        //     ckApprove.ID = "chkDetails_" + e.Row.DataItemIndex;
        //     cells[7].Controls.Add(ckApprove);
        // }
    }

    private void SaveFiles(string FolderName)
    {
        //for (int x = 0; x < this.GridViewResult.Rows.Count; x++)
        for (int x = 0; x < ResultDocuments.Count; x++)
        {
            //CheckBox CheckBoxDetails = (CheckBox)this.GridViewResult.Rows[x].Cells[7].Controls[0];
            //if (CheckBoxDetails.Checked)
            {
                string[] filename = SwissArmy.StringSplit(ResultDocuments[x].FileName, "\\");
                CreateFile(Server.MapPath("ReportsOutput\\" + FolderName + "\\" + ResultDocuments[x].ClaimCode + "-" + filename[filename.Length - 1].ToString()), ResultDocuments[x].BufferContent);
            }
            Thread.Sleep(300);
        }
    }

    #region comment code
    //public void Compress(FileInfo fi)
    //{
    //    // Get the stream of the source file.
    //    using (FileStream inFile = fi.OpenRead())
    //    {
    //        // Prevent compressing hidden and already compressed files.
    //        if ((File.GetAttributes(fi.FullName) & FileAttributes.Hidden)
    //                != FileAttributes.Hidden & fi.Extension != ".gz")
    //        {
    //            // Create the compressed file.
    //            using (FileStream outFile = File.Create(fi.FullName + ".gz"))
    //            {
    //                using (GZipStream Compress = new GZipStream(outFile, CompressionMode.Compress))
    //                {
    //                    // Copy the source file into the compression stream.
    //                    byte[] buffer = new byte[4096];
    //                    int numRead;
    //                    while ((numRead = inFile.Read(buffer, 0, buffer.Length)) != 0)
    //                    {
    //                        Compress.Write(buffer, 0, numRead);
    //                    }
    //                    Response.Write("Compressed From" + fi.Name + fi.Length.ToString() + "<br>");
    //                    Response.Write("Compress To" + outFile.Length.ToString() + "<br>");
    //                }
    //            }
    //        }
    //    }
    //}

    //public void Compress(string dirpath)
    //{
    //    //// Get the stream of the source file.
    //    //using (FileStream inFile = fi.OpenRead())
    //    {
    //        //// Prevent compressing hidden and already compressed files.
    //        //if ((File.GetAttributes(fi.FullName) & FileAttributes.Hidden)
    //        //        != FileAttributes.Hidden & fi.Extension != ".gz")
    //        {
    //            // Create the compressed file.
    //            using (FileStream outFile = File.Create(dirpath + "Testing.gz"))
    //            {
    //                using (GZipStream Compress = new GZipStream(outFile, CompressionMode.Compress))
    //                {
    //                    // Copy the source file into the compression stream.
    //                    DirectoryInfo di = new DirectoryInfo(dirpath);
    //                    foreach (FileInfo fi in di.GetFiles())
    //                    {
    //                        FileStream inFile = fi.OpenRead();
    //                        byte[] buffer = new byte[4096];
    //                        int numRead;
    //                        while ((numRead = inFile.Read(buffer, 0, buffer.Length)) != 0)
    //                        {
    //                            Compress.Write(buffer, 0, numRead);
    //                        }
    //                    }
    //                    //Response.Write("Compressed From" + fi.Name + fi.Length.ToString() + "<br>");
    //                    Response.Write("Compress To" + outFile.Length.ToString() + "<br>");
    //                }
    //            }
    //        }
    //    }
    //}

    //public void Decompress(FileInfo fi)
    //{
    //    // Get the stream of the source file.
    //    using (FileStream inFile = fi.OpenRead())
    //    {
    //        // Get original file extension, for example "doc" from report.doc.gz.
    //        string curFile = fi.FullName;
    //        string origName = curFile.Remove(curFile.Length - fi.Extension.Length);

    //        //Create the decompressed file.
    //        using (FileStream outFile = File.Create(origName))
    //        {
    //            using (GZipStream Decompress = new GZipStream(inFile,
    //                    CompressionMode.Decompress))
    //            {
    //                //Copy the decompression stream into the output file.
    //                byte[] buffer = new byte[4096];
    //                int numRead;
    //                while ((numRead = Decompress.Read(buffer, 0, buffer.Length)) != 0)
    //                {
    //                    outFile.Write(buffer, 0, numRead);
    //                }
    //                Response.Write("Decompressed: {0}" + fi.Name);
    //            }
    //        }
    //    }
    //}

    //private void Testing_CompressDecompress()
    //{
    //    // Path to directory of files to compress and decompress.
    //    string dirpath = "D:\\myfolder";

    //    DirectoryInfo di = new DirectoryInfo(dirpath);

    //    // Compress the directory's files.
    //    foreach (FileInfo fi in di.GetFiles())
    //    {
    //        Compress(fi);
    //    }

    //    // Decompress all *.gz files in the directory.
    //    foreach (FileInfo fi in di.GetFiles("*.gz"))
    //    {
    //        Decompress(fi);
    //    }
    //}
#endregion

    /*public bool AddZip(string FileName, string ZipFileName, string FolderName)
    {
        try
        {
            Shell32.ShellClass sc = new Shell32.ShellClass();
            Shell32.Folder SrcFlder = sc.NameSpace(Server.MapPath("ReportsOutput\\") + FolderName + "\\");
            //Shell32.FolderItem fi = SrcFlder.Items().Item(FileName);
            Shell32.FolderItems fis = SrcFlder.Items();
            Shell32.Folder DestFlder = sc.NameSpace(ZipFileName);
            DestFlder.CopyHere(fis, 128);
            Thread.Sleep(3000);
        }
        catch (Exception ignore)
        {
            this.ShowErrorMessage(ignore.Message);
            return false;
        }

        return true;
    }*/

    /*public bool CreateZip(string ZipFileName)
    {
        try
        {
            //Create an empty zip file
            byte[] emptyzip = new byte[] { 80, 75, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
            FileStream fs = File.Create(ZipFileName);
            fs.Write(emptyzip, 0, emptyzip.Length);
            fs.Flush();
            fs.Close();
            fs = null;
        }
        catch (Exception ex)
        {
            return false;
        }
        return true;
    }*/

    public bool CreateFile(string PathFileName, byte[] FileContent)
    {
        try
        {
            //SwissArmy.FileCreate(PathFileName, System.Text.Encoding.UTF8.GetString(FileContent));
            FileStream fs = File.Create(PathFileName);
            fs.Write(FileContent, 0, FileContent.Length);
            fs.Flush();
            fs.Close();
            fs = null;
        }
        catch (Exception ex)
        {
            this.ShowErrorMessage("Create supporting document error: " + ex.Message);
            return false;
        }
        return true;
    }

}

